package net.wicp.tams.common.binlog.alone.annotation;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import net.wicp.tams.common.Conf;
import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.binlog.alone.BinlogStart;
import net.wicp.tams.common.binlog.alone.BusiAssit;
import net.wicp.tams.common.exception.ExceptAll;
import net.wicp.tams.common.exception.ProjectExceptionRuntime;
import net.wicp.tams.common.spring.autoconfig.beans.TypeBean;

public class BinlogListenerDo extends TypeBean<Object> {
	private final static List<String> confs = new ArrayList<String>();

	public BinlogListenerDo(Annotation annotationInst) {
		super(annotationInst);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		BinlogListener binlogListener = (BinlogListener) super.annotationInst;
		if (binlogListener != null) {
			Properties props = new Properties();
			String preStr = String.format("common.binlog.alone.conf.%s.", binlogListener.conf());
			if (StringUtil.isNotNull(binlogListener.groupId())) {
				props.put(preStr + "groupId", binlogListener.groupId());
			}
			if (StringUtil.isNotNull(binlogListener.haType())) {
				props.put(preStr + "haType", binlogListener.haType());
			}
			props.put(preStr + "chk", binlogListener.chk());
			if (StringUtil.isNotNull(binlogListener.ip())) {
				props.put(preStr + "ip", binlogListener.ip());
			}
			props.put(preStr + "port", String.valueOf(binlogListener.port()));
			if (StringUtil.isNotNull(binlogListener.user())) {
				props.put(preStr + "user", binlogListener.user());
			}
			if (StringUtil.isNotNull(binlogListener.password())) {
				props.put(preStr + "password", binlogListener.password());
			}
			if (StringUtil.isNotNull(binlogListener.dbPattern())) {
				props.put(preStr + "dbPattern", binlogListener.dbPattern());
			}
			if (StringUtil.isNotNull(binlogListener.tbPattern())) {
				props.put(preStr + "tbPattern", binlogListener.tbPattern());
			}
			props.put(preStr + "rds", String.valueOf(binlogListener.rds()));
			props.put(preStr + "clientId", String.valueOf(binlogListener.clientId()));
			if (StringUtil.isNotNull(binlogListener.pos_gtids())) {
				props.put(preStr + "pos.gtids", binlogListener.pos_gtids());
			}
			props.put(preStr + "listener", super.getRef().getClass().getName());// 添加监听类
			try {
				String confId = binlogListener.conf();
				if (confs.contains(confId)) {
					throw new RuntimeException("已启动此confId的配置，请检查有相同的confId:【" + confId + "】");
				}
				Conf.overProp(props);
				BinlogStart.listeningNonBlocking(BusiAssit.configMap(confId));
				confs.add(confId);
			} catch (Exception e) {// 可能没有引入common-binlog-alone
				throw new ProjectExceptionRuntime(ExceptAll.project_nosupport, e);
			}
		}

	}

}
